package com.joycessh.search.index.service.impl;

import com.joycessh.search.index.entity.Page;
import com.joycessh.search.index.entity.PageInfo;
import com.joycessh.search.index.service.IndexService;
import com.joycessh.search.index.util.IndexReaderUtil;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer4Lucene7;

import java.io.IOException;
import java.util.List;

/**
 * @Author Joycessh
 * @Description
 * @Date 5/3/19 4:29 PM
 */
@Service(value = "indexService")
public class IndexServiceImpl implements IndexService {

    private static final Logger LOG = LoggerFactory.getLogger(IndexServiceImpl.class);

    @Override
    public PageInfo search(int pageNum, int pageSize, String value) throws IOException, ParseException, InvalidTokenOffsetsException {

        //检索字段
        String[] fileds = new String[]{"title", "content"};

        //创建分词器
        LOG.info("创建分词器");
        Analyzer analyzer = new IKAnalyzer4Lucene7();

        //指定搜索字段和分析器
        LOG.info("指定搜索字段和分析器");
        QueryParser queryParser = new MultiFieldQueryParser(fileds, analyzer);

        //用户输入内容
        LOG.info("用户输入内容是: " + value);
        Query query = queryParser.parse(value);
        return IndexReaderUtil.executeQuery(pageNum, pageSize, query);
    }
}
